(function(){
	/**
	 * 定义$代表jQuery对象
	 */
	var $ = jQuery;
	/**
	 * 坐席标识1,营业员标识0
	 */
	var jobCode = "0";
	/**
	 * 当前用户userid
	 */
	var userId = "";
	/**
	 * 当前用户userName
	 */
	var userName="";
	/**
	 * 当前用户对象
	 */
	var userInfoObj;
	/**
	 * 忙碌标识
	 */
	var busyCode = "1";
	/**
	 * 在线标识
	 */
	var onlineCode = "0";
	/**
	 * 闪烁效果
	 */
	var seatIsIn = "seatInFlash1";
    var iFlash = setInterval(function () {
        if (seatIsIn === "seatInFlash1") {
            $('.' + seatIsIn).removeClass(seatIsIn).addClass("seatInFlash2");
            seatIsIn = "seatInFlash2";
        } else {
            $('.' + seatIsIn).removeClass(seatIsIn).addClass("seatInFlash1");
            seatIsIn = "seatInFlash1";
        }
    }, 500);
    
    var timerArr;
    var title_text = $("title").text();
    $.extend({
		/**
		 * 调用方法
		 * $.blinkTitle.show();
		 * $.blinkTitle.clear();
		 */
		blinkTitle : {
			show : function() {	//有新消息时在title处闪烁提示
				var step=0, _title = title_text;
	
				var timer = setInterval(function() {
					step++;
					if (step==3) {step=1};
					if (step==1) {document.title='【　　　】'+_title};
					if (step==2) {document.title='【新消息】'+_title};
				}, 500);
				timerArr = [timer, _title];
			},
			/**
			 * @param timerArr[0], timer标记
			 * @param timerArr[1], 初始的title文本内容
			 */
			clear : function() {	//去除闪烁提示，恢复初始title文本
				if(timerArr) {
					clearInterval(timerArr[0]);	
					document.title = timerArr[1];
				};
			}
		}
	});
    
    /**
     * ready
     */
    $(function(){
    	var CurrentActive;
    	$(window).focus(function() {
    	    //处于激活状态
    		$.blinkTitle.clear();
    		CurrentActive = false;
    	});
    	$(window).blur(function() {
    	    //处于未激活状态
    		CurrentActive = true;
    	});
	/**
	 * 连接大厅的socket
	 */
	var hallSocket = io.connect('http://' + _host + ':' + _port + '/hall');
	
	/**
	 * 连接大厅后，触发connChatRoom方法</br>
	 */
	var connectHandler = function() {
		/**
		 * 监听leaveInfo，验证重复登录
		 * 监听userList，首次进入监听，获取所有在线用户
		 * 监听addUserToList，坐席已在线，当有新用户进入时，刷新列表
		 */
		hallSocket.emit("connChatRoom", userId, jobCode);
    };
    
    /**
     * 重复登录处理-[leaveInfo]
     */
    var leaveInfoHandler = function(_leaveInfoMsg){
    	var targetId = $("#hid_seatId").val();
    	output(_leaveInfoMsg, "lvEdit", "系统");
    	output(_leaveInfoMsg,targetId,"系统");
    	$("#seatList").empty();
    	$("#seatInfo").empty();
    	$("#visitInfo").empty();
    };
    

    /**
     * 初始化UE
     */
   
    function initUE(id) {
    	var _content;
    	$("textarea[name='"+(UEDITOR_CONFIG.textarea?UEDITOR_CONFIG.textarea:'editorValue')+"']").remove();
    	var ue1;
    	if(id){
    		ue1 = UE.getEditor('editor_'+id);
    	}else {
			ue1 = UE.getEditor('editor');
		}
    	
    	if(ue1){
    		_content = ue1.getContent();
    		ue1.destroy();
    	}
    	var $bgArea = $(".l_service_bj_"+id);
    	$bgArea.empty();
    	var $editor;
    	if(id){
    		$editor = $("<div id = 'editor_"+id+"'></div>");
    	}else{
    		$editor = $("<div id = 'editor'></div>");
    	}
    	var _w;
    	if(id){
    		_w = $(".l_service_bj_"+id).width();
    	}else{
    		_w = $(".l_service_bj").width();
    	}
    	//console.log(_w-1);
		$editor.css({
			width:(_w-1),
			height:167
		});
		$bgArea.append($editor);
		if(id){
			setTimeout(function(){
				var ue = UE.getEditor('editor_'+id,{ 
					initialFrameWidth : (_w-1),
			        initialFrameHeight: 167,
			        basePath:basePath
				});
				ue.ready(function(){
					if(_content){
						ue.setContent(_content);
					}
				});
				
			},10);
		}else{
			setTimeout(function(){
				var ue = UE.getEditor('editor',{ 
					initialFrameWidth : (_w-1),
			        initialFrameHeight: 167,
			        basePath:basePath
				});
				ue.ready(function(){
					if(_content){
						ue.setContent(_content);
					}
				});
				
			},10);
		}
	
		
    }
      /*  ue.commands['sendInfo'] = function(){
            alert('sdf');
        };

        ue.addshortcutkey({
            "sendInfo" : "ctrl+18"//enter
        });*/

    
    /**
     * 点击客服列表事件
     */
    var seatLiClick = function(){
    	/*//如果默认chatTemplete存在，则remove
    	var $defaultChatContainer = $("#defaultChatContainer");
    	if($defaultChatContainer){
    		$defaultChatContainer.remove();
    	}*/
    	$this = $(this);
    	var _seatId = $this.attr("userid");
    	$(document).off(".send_"+_seatId);
		$(document).on('click.send_'+_seatId,'.l_service_cz_button_'+_seatId,sendMessageHandler);
    	//$(".l_service_cz_button_"+_seatId).live("click",sendMessageHandler);
    	//清楚所有li的所有样式
    	var expiredSeatId = $("#hid_seatId").val();
    	//如果点击的li跟当前会话的li不同
    	if(expiredSeatId&&(expiredSeatId!=_seatId)){
    		//隐藏过期chatTemplete
    		var $expiredSeatTemplate = $(".chatContainer_" + expiredSeatId);
    		//删除过期的div
    		$expiredSeatTemplate.hide();
    		//过期seatID
    		var $expiredSeatLi = $('li.li_id_' + expiredSeatId);
    		//清除等待样式
    		$expiredSeatLi.removeClass("visit_wait_response");
    		//清除闪烁样式
    		$expiredSeatLi.removeClass("seatIsIn");
    		$expiredSeatLi.removeClass("seatInFlash1");
    		$expiredSeatLi.removeClass("seatInFlash2");
    		//清除当前会话class
    		$expiredSeatLi.removeClass("currentChat");
    		//清空坐席信息
    		$("#seatInfo").empty();
    		//清除title信息
    		$("#titleInfo_"+expiredSeatId).empty();
    		//通知坐席，营业员离开
    		hallSocket.emit("visitIsLeave",userId,expiredSeatId);
    	}
    	
    	var $seatLi = $('li.li_id_' + _seatId);
    	if(!$seatLi.hasClass("currentChat")){
    		//注册请求连接事件
        	hallSocket.emit('visitRequestConnect',userId,_seatId);
        	//添加等待连接样式
        	$seatLi.addClass("visit_wait_response");
        	$("#hid_seatId").val(_seatId);
    	}
    	$seatLi.addClass("currentChat");
    	var $chatContainer = $(".chatContainer_" + _seatId);
    	$(".chatContainer").hide();
    	$chatContainer.show();
        //initUE(_seatId);
    	$(window).resize();
    };
    
    /**
     * 添加用户信息至坐席列表
     */
    var addUserToSeat = function(userVo,_status){
    	var $userLi = $('li.userChatItems_' + userVo.id);
    	if($userLi.length>0){
    		return;
    	}
    	$("#seatList").append($.format(seatLi,userVo.id,userVo.username,userVo.dept));
    	/**
    	 * 给列表的li添加点击事件
    	 */
    	$(".li_id_"+userVo.id).on('click',seatLiClick);
    	
    	 var $templateContent = $('#chatTemplate');
         var data = [
             {uid: userVo.id,uName:userVo.username}
         ];
         var chatContainer = $(".chatContainer_"+userVo.id);
         if(chatContainer.length<1){
        	 $templateContent.tmpl(data).appendTo($('#chatContainers'));
         }
         
    };
    
    
    /**
     * 营业员离线，刷新用户列表-[removeUserToList]
     */
    var removeUserToListHandler = function(_userVo){
    	var userVo = eval("(" + _userVo + ")");
    	var _userId = userVo.id;
    	var $userLi = $('li.userChatItems_' + _userId);
    	$userLi.remove();
    	//hallSocket.emit("userIsLeave",_userId);
    };
    
    /**
     * 首次进入监听，获取所有在线用户-[userList]
     */
    var userListHandler = function(_ulstMap){
    	var ulstObj = eval("(" + _ulstMap + ")");
    	 $.each(ulstObj,function(key,values){
    		var userVo = ulstObj[key];
 		    if(userVo.jobCode==="1"){
 		    	addUserToSeat(userVo,onlineCode);
 		    }
    	 });  
    	
    };
    
    /**
     * 营业员已在线，当有新用户进入时，刷新列表-[addUserToList]
     */
    var addUserToListHandler = function(_userVo){
    	var userVo = eval("(" + _userVo + ")");
    	if(userVo.jobCode==="1"){
    		addUserToSeat(userVo,onlineCode);
    	}
    };
    /**
     * 显示更新同时在线人数
     */
    var userCountHandler = function(_count){
    	$("#userCount").html("当前在线人数：" + _count);
    };
    
    /**
     * 输出错误信息-[errorMsg]
     */
    var errorHandler = function(_errorMsg){
    	var targetId = $("#hid_seatId").val();
    	if(targetId){
    		output(_errorMsg, targetId, "系统");
    	}else{
    		output(_errorMsg, "lvEdit", "系统");
    	}
    };
    /**
     * 点击即取消提醒
     */
    var cancelFlash = function(){
    	$this = $(this);
    	var _seatId = $this.attr("userid");
    	var $seatLi = $("li.li_id_" + _seatId);
    	$seatLi.removeClass("seatIsIn");
    	$seatLi.removeClass("seatInFlash1");
    	$seatLi.removeClass("seatInFlash2");
    };
    /**
     * 提交评价
     */
    var submitEvaluation = function(){
    	var _seatId = $(this).attr("seatid");
    	var _score = $(this).attr("ev");
    	var _scoreText = $(this).text();
    	hallSocket.emit('saveScoreInfo',userId,_seatId,$("#hid_evalId").val(),_score,_scoreText);
    };
    
    /**
     *坐席应答营业员处理-[seatResponseVisit] 
     */
    var seatResponseHandler = function(_seatUser){
    	//连接坐席信息
    	$seatUserObj = eval("(" + _seatUser + ")");
    	var _seatId = $seatUserObj.id;
    	var $seatLi = $("li.li_id_" + _seatId);
    	
    	$seatLi.removeClass("visit_wait_response");
    	//坐席连接，坐席列表闪烁
    	$seatLi.addClass(seatIsIn);
    	//填充坐席信息
    	$seatInfo = $("#seatInfo");
    	$seatInfo.empty();
    	var $seatTemplate = $("#seatTemplate");
    	$seatTemplate.tmpl($seatUserObj).appendTo($seatInfo);
    	//更新title提示信息
    	$titleInfo = $("#titleInfo_"+_seatId);
    	$titleInfo.empty();
    	var $titleInfoTemplate = $("#titleInfoTemplate");
    	$titleInfoTemplate.tmpl($seatUserObj).appendTo($titleInfo);
    	$("#hid_seatId").val(_seatId);
    	//给li添加点击事件
    	$seatLi.live('click',cancelFlash);
    	//获取链接
    	hallSocket.emit('saveScoreInfo',userId,_seatId);
    	//给链接添加点击事件
    	$(".evaluationLink").live("click",submitEvaluation);
    	$(document).off(".his_btn_"+_seatId);
		$(document).on('click.his_btn_'+_seatId,'#his_btn_'+_seatId,function(){
			if(!$("#his_date_"+_seatId).val()){
				alert("请选择日期");
				return;
			}
			
			hallSocket.emit('historyInfoShow',userId,_seatId,$("#his_date_"+_seatId).val());
		});
    };
    
    /**
     * 发送消息-[sendMessage]
     */
    window.sendMessageHandler = sendMessageHandler = function(){
    	
    	var _seatId = $("#hid_seatId").val();
    	var $userLi = $('li.userChatItems_' + _seatId);
    	if($userLi.hasClass("visit_wait_response")){
    		alert("您已请求坐席，请等待坐席应答！");
    		return;
    	}
    	var visitUE = UE.getEditor('editor_'+_seatId);
    	var message = visitUE.getContent();
    	if(!message){
    		alert("请不要发送空消息！");
    		return;
    	}
    	var jsonObject = {'@class': 'com.zx.chatroom.vo.Chat',
    			fromUserId : userId, 
    			fromUserName : "", 
				toUserId : _seatId,
				toUserName : "",
				message : message};
		hallSocket.json.send(jsonObject);
		//清除消息闪烁
    	$.blinkTitle.clear();
    };
    
    /**
     * 监听接收消息，所有监听到的消息，都是发给自己的-[receiveMessage]
     */
    var receiveMessageHandler = function(_message){
    	var chatObj = eval("(" + _message + ")");
    	var message = chatObj.message;
    	if(chatObj.fromUserId === userId){
    		output(message, chatObj.toUserId, chatObj.fromUserName);
    		var ue = UE.getEditor('editor_'+chatObj.toUserId);
        	ue.setContent("");
    	}else if(chatObj.toUserId === userId){
    		output(message, chatObj.fromUserId, chatObj.fromUserName);
    		var ue = UE.getEditor('editor_'+chatObj.fromUserId);
        	ue.setContent("");
        	//新消息闪烁
        	if (CurrentActive) {
        		$.blinkTitle.clear();
        		$.blinkTitle.show();
			}
    	}
    };
    /**
     * 显示评价信息
     */
    var scoreInfoHandler = function(_scoreInfo){
    	var scoreObj = eval("(" + _scoreInfo + ")");
    	var sUser = eval("(" + scoreObj.sId + ")");
    	output(scoreObj.info,sUser.id,sUser.username);
    };
    /**
     * 获取评价ID
     */
    var ScoreInfoIDHandler = function(_evalId){
    	$("#hid_evalId").val(_evalId);
    };
    
    /**
     * 打印评价成功消息
     */
    var evalSuccessHandler = function(_msgInfo){
    	var msgObj = eval("(" + _msgInfo + ")");
    	var sUser = eval("(" + msgObj.sId + ")");
    	output(msgObj.info,sUser.id,sUser.username);
    	var $seatLi = $('li.li_id_' + sUser.id);
    	$seatLi.removeClass("visit_wait_response");
		//清除闪烁样式
    	$seatLi.removeClass("seatIsIn");
    	$seatLi.removeClass("seatInFlash1");
    	$seatLi.removeClass("seatInFlash2");
		//清除当前会话class
    	$seatLi.removeClass("currentChat");
    	$("#seatList").empty();
    	$("#seatInfo").empty();
    	$("#visitInfo").empty();
    };
    
    /**
     * resize的时候，重新初始化编辑器
     */
    $(window).resize(function(){
    	var $hid_seatId =  $("#hid_seatId");
    	//if($hid_seatId.val()){
    		initUE($hid_seatId.val());
    	//}
    });
    /**
     * 坐席同时接待人数
     */
    var sizeHandler = function(_sizeInfo){
    	var sizeObj = eval("(" + _sizeInfo + ")");
    	var seatId = sizeObj.seatId;
    	var _size = sizeObj.size;
    	if(_size > 5){
    		var $seatLi = $('li.li_id_' + seatId);
    		$seatLi.addClass("isBusy");
    	}else{
    		var $seatLi = $('li.li_id_' + seatId);
    		$seatLi.removeClass("isBusy");
    	}
    };
    /**
     * 显示截图
     */
    var snapscreenPathHandler = function(jsonInfo){
    	var snapObj = eval("(" + jsonInfo + ")");
    	var snapscreenPath = snapObj.imgSrc;
    	var userName = snapObj.fromUserName;
    	var targetId = $("#hid_seatId").val();
    	var ue = UE.getEditor('editor_'+targetId);
    	ue.setContent(snapscreenPath);
    	//output(snapscreenPath,targetId,userName);
    };
    
    var userLeaveMessageHandler = function(chatJson){
    	var chatObj = eval("(" + chatJson + ")");
    	var _seatId = $("#hid_seatId").val();
    	//alert(chatObj.message);
    	output(chatObj.message,"lvEdit","系统");
    	output(chatObj.message,_seatId,"系统");
    };
    /**
     * 转接用户
     */
    var adapterMeHandler = function(seatUserVoJson){
    	var seatUserVo = eval("(" + seatUserVoJson + ")");
    	var _seatId = seatUserVo.id;
    	$("#hid_seatId").val(_seatId);
    	
    	$(".userChatLi").removeClass("visit_wait_response");
    	$(".userChatLi").removeClass("seatIsIn");
    	$(".userChatLi").removeClass("seatInFlash1");
    	$(".userChatLi").removeClass("seatInFlash2");
    	$(".userChatLi").removeClass("currentChat");
    	var $adapterUser = $('li.li_id_' + _seatId);
    	$adapterUser.addClass("currentChat");
    	
    };
		
		$userInfoObj = eval("(" + $("#hid_userInfo").val() + ")");
		userId = $userInfoObj.id;
		userName = $userInfoObj.username;
		$("#jumpLink").append("<a href=\"talk?baseId="+userId+"\" target=\"_blank\">进入群组</a>");
		
		$visitInfo = $("#visitInfo");
		$visitInfo.empty();
		var $visitTemplate = $("#visitTemplate");
		$visitTemplate.tmpl($userInfoObj).appendTo($visitInfo);
		/**
		 * 截图插件
		 */
	
			 function plugin0()
			    {
			        return document.getElementById('plugin0');
			    }
			
			    plugin = plugin0;
			    
			    function snapshot(){
			    	 if(undefined==plugin().snapshot){
						 $("#dialog_info").show();
					 }else{
							var seatId = $("#hid_seatId").val();
					    	if(seatId){
					    		plugin().snapshot($("#localAddr").val(),"/chatroomV2/snapscreenUp/"+userId+"/"+seatId+"/hall",$("#localPort").val());
					    	}
					 }
			    }
			    $(document).off(".snapshotButtonClick");
			    $(document).on("click.snapshotButtonClick",".snapshotButton",snapshot);
			    
			    $(document).off(".dialogCloseClick");
			    $(document).on("click.dialogCloseClick",".t_pic",function(){
			    	$("#dialog_info").hide();
			    });
		 
		
		/**
		 * 页面加载完成，连接大厅
		 */
		hallSocket.on('connect', connectHandler);
		/**
		 * 监听重复登录
		 */
		hallSocket.on('leaveInfo',leaveInfoHandler);
		/**
		 * 首次进入监听，获取所有在线用户
		 */
		hallSocket.on('userList',userListHandler);
		/**
		 * 坐席已在线，当有新用户进入时，刷新列表
		 */
		hallSocket.on('addUserToList',addUserToListHandler);
		
		/**
		 * 监听同时在线人数变化-[addUserToList]
		 */
		hallSocket.on('userCount',userCountHandler);
		
		/**
		 * 营业员离线
		 */
		hallSocket.on('removeUserToList',removeUserToListHandler);
		/**
		 * 错误信息
		 */
		hallSocket.on('errorMsg',errorHandler);
		/**
		 * 监听坐席应答
		 */
		hallSocket.on('seatResponse',seatResponseHandler);
		/**
		 * 接收消息
		 */
		hallSocket.on('receiveMessage',receiveMessageHandler);
		/**
		 * 监听评价
		 */
		hallSocket.on('scoreInfo',scoreInfoHandler);
		/**
		 * 获取评价ID
		 */
		hallSocket.on('ScoreInfoID',ScoreInfoIDHandler);
		/**
		 * 打印评价成功消息
		 */
		hallSocket.on('evalSuccess',evalSuccessHandler);
		/**
		 * 用户离开，打印离开消息
		 */
		hallSocket.on('userLeaveMessage',userLeaveMessageHandler);
		/**
		 * 坐席接待人数
		 */
		hallSocket.on('seatSize',sizeHandler);
		/**
		 * 上传截图
		 */
		hallSocket.on("snapscreenPath",snapscreenPathHandler);
		/**
		 * 转接
		 */
		hallSocket.on("adapterMe",adapterMeHandler);
		/**
		 * 显示历史记录
		 */
		hallSocket.on('hisInfo',function(json){
			//放到隐藏div里
			var _seatId = $("#hid_seatId").val();
			$("#lvEdit_"+_seatId).removeClass("l_serviceHidden");
			
			var $closeBtn = $(".serviceList_close_btn_"+_seatId);
			$("#lvEdit_"+_seatId).html("");
			$("#lvEdit_"+_seatId).html("<span style ='color:red'>历史记录</span><br/>"+json);
			$closeBtn.removeClass("serviceList_close_btn");
			$closeBtn.addClass("serviceList_close_btn_show");
			$("#lvEdit_"+_seatId).show();
			$closeBtn.show();
			$(document).off(".closeBtn_"+_seatId);
			$(document).on('click.closeBtn_'+_seatId,'.serviceList_close_btn_'+_seatId,function(){
				$("#lvEdit_"+_seatId).hide();
				$closeBtn.hide();
			});
			
		});
	});
	
    /**
	 * 聊天窗口div自动滚动至底部
	 */
	function scollToButtom(elementId) {
        $("#" + elementId).animate({
            scrollTop: $("#" + elementId)[0].scrollHeight
        }, 1000);
    }
	
	/**
	 * @param message 输出信息
	 * @param targetId 输出信息打印区域元素ID
	 * @param userName 信息输出者NAME
	 */
	var output = function(_message, _targetId, _userName) {
        var currentTime = "<span class='time'>" + moment().format('HH:mm:ss') + "</span>";
        var element = $("<div>" + currentTime + " " + _message + "</div>");
        if (!_targetId) {
        	_targetId = "lvEdit";
        } else {
            element = $("<div>" + currentTime + " " + _userName + "：" + _message + "</div>");
        }
        $("#" + _targetId).append(element);
        scollToButtom(_targetId);
    };
}).call(this);

/**
 * 坐席列表li
 */
var seatLi = "<li userid='{0}' class='userChatLi userChatItems_{0} li_id_{0}' title='{2}'><a class='linkChat' userid='{0}' href='#'><span></span>{1}({2})</a></li>";
